//
//  JRImageCompressionManager.swift
//  CaidaProject
//
//  Created by 京睿 on 2017/3/21.
//  Copyright © 2017年 HOME Ma. All rights reserved.
//

import Foundation
import UIKit

extension UIImage {
    public var jMemsize: Double {
        guard let imageData = UIImageJPEGRepresentation(self, 1) else { return 0 }
        let size: Double = Double(imageData.count) / 1000.0
        return size
    }
    
    var jDataValue: Data! {
        return UIImageJPEGRepresentation(self, 1)
    }
}

/// 图片压缩
public final class JRImageCompressionManager {
    
    public typealias JRImageCompressionCompleted   = @convention(block)(UIImage?, Data?)->()
    
    public class func JRCompress(_ images: [UIImage], expect memSize: Double, scale: CGFloat = 1, stride: CGFloat = 0.1, completed: @escaping ([(UIImage, Data)])->()) {
        var results = [(UIImage, Data)]()
        var flag = 0
        images.enumerated().forEach { (index, image) in
            results.append((UIImage(), Data()))
            JRCompress(image, expect: memSize, scale: scale, stride: stride, completed: { (s1, s2) in
                results[index] = (s1!, s2!)
                flag += 1
                if flag == images.count {
                    DispatchQueue.main.async {
                        completed(results)
                        return
                    }
                }
            })
        }
    }
    
    /// 图片压缩
    ///
    /// - Parameters:
    ///   - image: 需要压缩的图片
    ///   - memSize: 预期大小 单位Kb
    ///   - scale: 默认初始压缩比例 默认为1不压缩
    ///   - stride: 压缩步长 每次递减10%
    ///   - completed: 压缩完成获取压缩后的图片
    public class func JRCompress(_ image: UIImage, expect memSize: Double, scale: CGFloat = 1, stride: CGFloat = 0.1, completed: @escaping JRImageCompressionCompleted) {
        DispatchQueue.global().async {
            autoreleasepool {
                guard let imageData = UIImageJPEGRepresentation(image, scale) else {
                    DispatchQueue.main.async {
                        completed(image, image.jDataValue)
                    }
                    return
                }
                guard let nextImage = UIImage.init(data: imageData) else {
                    DispatchQueue.main.async {
                        completed(image, image.jDataValue)
                    }
                    return
                }
                
                let originSize = nextImage.size
                let newSizeW = originSize.width * scale
                let newSizeH = originSize.height * scale
                let newSize = CGSize.init(width: newSizeW, height: newSizeH)
                UIGraphicsBeginImageContext(newSize)
                nextImage.draw(in: CGRect.init(origin: CGPoint.zero, size: newSize))
                guard let finalImage = UIGraphicsGetImageFromCurrentImageContext() else {
                    DispatchQueue.main.async {
                        completed(image, image.jDataValue)
                    }
                    return
                }
                UIGraphicsEndImageContext()
                
                if finalImage.jMemsize > memSize {
                    let nextScale = scale - stride
                    JRCompress(image, expect: memSize, scale: nextScale, stride: stride, completed: completed)
                } else {
                    print("\(finalImage.jMemsize), \(finalImage.jMemsize)")
                    DispatchQueue.main.async {
                        completed(finalImage, finalImage.jDataValue)
                    }
                }
            }
        }
    }
    
    private func compress(origin: UIImage, expect: Double) {
        let originMem = origin.jMemsize
        if originMem <= expect {
            dump("结束")
            return
        }
        let originSize = origin.size
        
        
    }
    
    private func cn(expect: Double, scale: Double) -> Bool {
        
        return false
    }
}
